const indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB
let request
let db

/**
 * 创建数据库
 * dbname 数据库名
 * name 存储空间名
*/
export function initDb(dbname, name) {
  return new Promise((resolve, reject) => {
    request = indexedDB.open(dbname, 1)
    request.onsuccess = function(event) {
      db = event.target.result
      db.onsuccess = function(event) {
        console.log('数据库操作成功!')
      }
      db.onerror = function(event) {
        console.error('数据库操作发生错误！', event.target.errorCode)
        reject(event)
      }
      // console.log('打开数据库成功!')
      resolve(db)
    }
    request.onupgradeneeded = (event) => {
      console.log('onupgradeneeded')
      const database = event.target.result
      const objectStore = database.createObjectStore(name, { keyPath: 'id' })
      objectStore.createIndex('key', 'key', { unique: true })
      objectStore.createIndex('value', 'value', { unique: false })
    //   resolve('ok')
    }
  })
}

/**
 * 创建对象存储空间和索引
 * name 存储空间的名称
*/
export function creat(name) {
  return new Promise((resolve, reject) => {
    // request.onupgradeneeded = (event) => {
    //   console.log(13213132)
    //   const database = event.target.result
    //   const objectStore = database.createObjectStore(name, { keyPath: 'id' })
    //   objectStore.createIndex('key', 'key', { unique: true })
    //   objectStore.createIndex('value', 'value', { unique: false })
    // }
    resolve('ok')
  })
}

export function add(name, data) {
  const objectStore = db.transaction([name], 'readwrite').objectStore(name)
  data.forEach((item, index) => {
    let request = objectStore.add(item)
    request.onsuccess = function(event) {
      // console.log('添加成功！', index)
    }
  })
}

export function readAll(name) {
  const objectStore = db.transaction(name).objectStore(name)
  let arr = []
  return new Promise((resolve, reject) => {
    objectStore.openCursor().onsuccess = (event) => {
      let cursor = event.target.result
      if (cursor) {
        arr.push(cursor.value)
        cursor.continue()
      } else {
        // console.log('没有更多数据了！')
        resolve(arr)
      }
    }
  })
}

export function close() {
  db.close()
}

export function del(dbName) {
  indexedDB.deleteDatabase(dbName)
}
